import api from '../../../api/index'
import dayjs from '../../../plugin/dayjs/index';
import { cloneDeep } from '../../utils/util'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageNum: 0,
		pageSize: 40,
    searchvalue: '',
    show: false,
    showDialog: false,
    selItem: {},
    time: null,
    value: 0,
    addList: [],
    showpopup: false,
    totalKcal: 0,
    dd: null,
    itemData:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var { time } = options
    if(time) {
      this.setData({
        dd: time
      })
    }
    this.getlist()
    // this.getlistdate()
  },
  getlistdate() {
    api.post('/api/hxhealth/sportrecord/list', {
      data: {
        "date": this.data.dd
      }
    }).then(res => {
      console.log(res);
      // console.log(JSON.stringify(res));
      if (res.length > 0) {
        let data = res
        let totalKcal = 0;
        for (let i = 0; i < data.length; i++) {
          totalKcal += parseFloat(data[i].kcal);
        }
        console.log('kcal总和：', totalKcal);
        console.log(res);
        this.setData({
          addList: res,
          totalKcal: totalKcal.toFixed(3)
        })
      } else {
        this.setData({
          addList: [],
          totalKcal: 0
        })
      }
    }).catch(e => {
      console.log(e)
    })
  },
  getlist(name) {
    api.post('/api/hxhealth/sportrecord/dict', {
      head: {
        firstresult: this.data.pageNum,
        maxresults: this.data.pageSize,
        bodytype: 'flat',
      },
        data: {
          name
        }
    }).then(res => {
        console.log(res);
        if (res.length == 0) { //请求的数据为空，没有数据
          if (this.data.pageNum == 0) { // 第一页都没有数据，直接显示暂无数据
            this.setData({
              noData: true
            })
          } else { // 不为第一页时，请求的数据为空，说明没有更多数据了，把pageNum减一，是为了下次触底可以继续请求刷新，万一有了新数据也可以正常显示出来
            this.setData({
              noMor: true,
              pageNum: 0,
              show: true
            })
          }
        } else {
          const dataList = [...this.data.itemData, ...res]
          console.log(dataList);
          if (res.length == this.data.pageSize) { // 请求的数据为10条，说明下一页可能还有数据，列表添加上新的数据，把其他状态设为不显示
            this.setData({
              itemData: dataList,
              noMor: false,
              noData: false,
              show: true
            })
          } else { 
            this.setData({
              itemData: dataList,
              show: true
            })
          }
        }
        
    }).catch(e => {
        console.log(e)
    })
  },
  doSelSportItem(e) {
    const { id } = e.currentTarget.dataset
    const findData = this.data.itemData.find(item => item.id === id)
    console.log(findData)
    const value = this.data.addList.find(item => item.id === id)
    this.setData({
      time: value ? value.duration : null,
      value: value ? value.kcal : 0,
      selItem: findData,
      showDialog: true
    })
  },
  inputTime(e) {
    if(e.detail && Number(e.detail) > 0) {
      const karValue = Number(e.detail) * Number(this.data.selItem.varheat)
      this.setData({
        time: Number(e.detail),
        value: karValue.toFixed(3)
      })
    } else {
      wx.showToast({
        icon: 'none',
        title: '请输入正整数'
      });
    }
  },
  onConfirm() {
    if(this.data.time && Number(this.data.time) > 0) {
      const obj = {
        // date: dayjs().format('YYYY-MM-DD'),
        date: this.data.dd,
        duration: this.data.time,
        id: this.data.selItem.id,
        kcal: this.data.value,
        sport: [this.data.selItem.id,this.data.selItem.name],
        sportimage: this.data.selItem.image,
      }
      const value = this.data.addList.find(item => item.id === this.data.selItem.id)
      if(value) {
        const cloneList = cloneDeep(this.data.addList)
        cloneList.forEach((item, index) => {
          if (item.id === this.data.selItem.id) {
            cloneList[index] = obj
          }
        })
        this.setData({
          addList: cloneList
        })
      } else {
        this.data.addList.push(obj)
      }
      console.log(this.data.addList, 'addList')
      let totalKcal = 0;
        for (let i = 0; i < this.data.addList.length; i++) {
          totalKcal += parseFloat(this.data.addList[i].kcal);
        }
        this.setData({
          totalKcal: totalKcal.toFixed(3)
        })
        console.log(totalKcal);
    } else {
      wx.showToast({
        icon: 'none',
        title: '请输入运动时间'
      });
    }
  },
  deleteSelSportItem(e) {
    console.log(e);
    console.log(this.data.totalKcal);
    let index = e.currentTarget.dataset.index
    // let id = e.currentTarget.dataset.id
    
    let data = this.data.addList
    // this.delete(id)
    data.splice(index, 1);
    console.log(data);
    this.setData({
      addList: data
    })
    let totalKcal = 0;
        for (let i = 0; i < this.data.addList.length; i++) {
          totalKcal += parseFloat(this.data.addList[i].kcal);
        }
        this.setData({
          totalKcal: totalKcal.toFixed(3)
        })
        console.log(totalKcal);
  },
  // delete(id) {
  //   try {
  //     api.get(`/api/hxhealth/sportrecord/remove/${id}`).then((res) => {
  //       console.log(res);
  //     });
  //   } catch (e) {
  //     console.error(e);
  //   }
  // },
  showPopup() {
    console.log('弹出',this.data.addList);
    this.setData({
      addList: this.data.addList
    })
    this.setData({ showpopup: true });
    // if(this.data.addList.length>0) {
    //   this.setData({ showpopup: true });
    // } else {
    //   // wx.showToast({
    //   //   icon: 'none',
    //   //   title: '请输入运动时间'
    //   // });
    // }
    
  },

  onClose() {
    this.setData({ showpopup: false });
  },
  svaeItem() {
    const data = this.data.addList
    console.log(data);
    if(data.length == 0) {
         wx.showToast({
        icon: 'none',
        title: '请添加运动'
      });
    }
    const updatedData = data.map(item => {
      const { id, ...rest } = item;
      return rest;
    });
    console.log(updatedData);
    api.post('/api/hxhealth/sportrecord/save', {
      data: updatedData
  }).then(res => {
      console.log(res);
      this.onClose()
      wx.navigateBack({
        delta: 1 //返回的页面数，如果 delta 大于现有页面数，则返回到首页,
      });
      // wx.navigateTo({ url: `/dietaryRecommendations/pages/sportsrecord/index?curDate=${this.data.dd}` });
  }).catch(e => {
      console.log(e)
  })
  },
  onCancelSearch() {
    this.getlist()
    console.log('quxiao' + this.data.searchvalue);
  },
  onChange(e) {
    this.setData({
      searchvalue: e.detail,
    });
  },
  onSearch() {
    this.setData({
      itemData: [],
      pageNum: 0,
      pageSize: 40,
    });
    console.log('搜索' + this.data.searchvalue);
    this.getlist(this.data.searchvalue)
  },
  godetailsPage(e) {
    let name = e.currentTarget.dataset.name
    wx.navigateTo({ url: `/dietaryRecommendations/pages/sportsrecorddetails/index?name=${name}` });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      itemData: [],
      noMor: false,
      noData: false,
			pageNum: 0,
			pageSize: 40,
		});
    this.getlist();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    console.log('到底了--------');
    if ((this.data.pageNum + 1) * this.data.pageSize == this.data.itemData.length) { 
      // 数据列表的数量刚好等于页数*每页条数，可以请求下一页
        this.setData({
          pageNum: this.data.pageNum + 1, // 一般上拉触底是为了加载更多分页数据，所以这里页数自增
        });
        // 查询列表方法
        this.getlist(); 
      } else { 
      // 数据列表的数量不等于页数*每页条数，说明当前页数据不足10条，已经没有更多数据了
        this.setData({
          noMor: true  // 这里在页面最底部显示一排文字，没有更多数据了
        })
      }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})